package com.gcc.web;

import com.gcc.pojo.User;
import com.gcc.service.UserService;
import com.gcc.service.impl.UserSeiviceImpl;
import com.gcc.test.UserServletTest;
import com.gcc.utils.WebUtils;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

public class UserServlet extends BaseServlet {
    private UserService userService=new UserSeiviceImpl();


    protected void ajaxExistsUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求的参数username
        String username = req.getParameter("username");
        //调用userService.existsUsername()；
        boolean existUsername = userService.existUsername(username);
        //把返回的结果封装成map对象
        Map<String,Object> reslutMap=new HashMap<>();
        reslutMap.put("existUsername",existUsername);
        Gson gson=new Gson();
        String json = gson.toJson(reslutMap);
        resp.getWriter().write(json);
    }
    /**
     * 注销
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     //销毁session中用户登录的信息(或销毁session)
        req.getSession().invalidate();
     // 重定向到首页(或登录页面)
        resp.sendRedirect(req.getContextPath());
    }
        /**
         * 处理登录
         * @param req
         * @param resp
         * @throws ServletException
         * @throws IOException
         */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        //获取请求参数
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        //调用userService处理业务
        User loginUser = userService.login(new User(null, username, password, null));
        if(loginUser==null)
        {
            //把错误信息，和回显的表单项信息，保存到request域中
            req.setAttribute("msg","用户名或者密码错误");
            req.setAttribute("username",username);
            //跳回登录页面
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);

        }
        else
        {
             req.getSession().setAttribute("user",loginUser);
            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req,resp);
        }

    }

    /**
     * 处理注册
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取session中的验证码
        String token= (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //删除session中的验证码
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        //1.获取请求参数
        String username =req.getParameter("username");
        String password =req.getParameter("password");
        String email =req.getParameter("email");
        String code =req.getParameter("code");


        User user=  WebUtils.copyParamToBean(req.getParameterMap(),new User());
        //检查 验证码是否正确  写死 要求验证码为abcde
        if(token!=null&&token.equalsIgnoreCase(code))
        { //正确 检查用户名是否可用
            if(userService.existUsername(username))
            {

                //将回显信息跳转到注册页面中
                req.setAttribute("msg","用户名已存在！！");
                req.setAttribute("username",username);
                req.setAttribute("email",email);
                //不可用 跳转到注册页面
                System.out.println("用户名["+username+"]已存在");
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);

            }
            else{
                userService.registarUser(new User(null,username,password,email));
                //可用 跳转到注册成功页面 regist_success.jsp
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req,resp);
            }


        }
        else {
            //将回显信息跳转到注册页面中
            req.setAttribute("msg","验证码错误！！");
            req.setAttribute("username",username);
            req.setAttribute("email",email);
            //不正确 调回注册页面
            System.out.println("验证码["+code+"]错误");
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
        }
    }
    /* @Override
   protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action=req.getParameter("action");


        try {
            Method method = this.getClass().getDeclaredMethod(action,HttpServletRequest.class,HttpServletResponse.class);

            method.invoke(this,req,resp);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }*/

    }
